const fs = require('fs');
const {
    resolve
} = require('path');
const superagent = require("superagent");
const readFilePro = file => {
    return new Promise((resolve, reject) => {
        fs.readFile(file, (err, data) => {
            if (err) reject('I could not find that file');
            resolve(data);
        })
    })
}
const writeFilePro = (file, data) => {
    return new Promise((resolve, reject) => {
        fs.writeFile(file, data, err => {
            if (err) reject("I could write file");
            resolve('success')
        })
    })
}
const getDogPic = async () => {
    try {
        const data = await readFilePro(`${__dirname}/dog.txt`);
        console.log(`Breed:${data}`);
        const res1 = superagent.get(`https://dog.ceo/api/breed/${data}/images/random`);
        const res2 = superagent.get(`https://dog.ceo/api/breed/${data}/images/random`);
        const res3 = superagent.get(`https://dog.ceo/api/breed/${data}/images/random`);
        const all = await Promise.all([res1,res2,res3]);
        const images = all.map(el=>{
            return el.body.message
        })
        //const res = await superagent.get(`https://dog.ceo/api/breed/${data}/images/random`);
       // console.log(res.body.message);
       
        await writeFilePro('dog-img.txt', images.join('\n'));
        console.log('Random dog image saved to file')
    } catch (err) {
        console.log(err);
        throw(err);
    }
    return '2:Ready '
}
(async() =>{
    try{
        console.log('111');
        const x = await getDogPic();
        console.log(x);
        console.log('333');
    }catch{
        console.log('Error')
    }
})();
/*
console.log('111')
const x = getDogPic().then(x=>{
    console.log(x);
    console.log('333')
})
.catch(err=>{
    console.log(err);
});
*/



/*
// 因为封装了一个promise对象 所以可以不使用函数内的promise对象无限包裹下去
readFilePro(`${__dirname}/dog.txt`).then((data)=>{
    console.log(`Breed:${data}`);
    return superagent.get(`https://dog.ceo/api/breed/${data}/images/random`)
})
.then((res)=>{
    console.log(res.body.message);
    return writeFilePro('dog-img.txt',res.body.message)
})
.then(()=>{
    console.log('Random dog image saved to file')
})
.catch((err)=>{
    console.log(err);
})
*/


// fs.readFile(`${__dirname}/dog.txt`, (err, data) => {
//     console.log(`Breed:${data}`);
//     superagent.get(`https://dog.ceo/api/breed/${data}/images/random`).end((err, res) => {
//         if(err) return console.log(err.message);
//         console.log(res.body);
//         fs.writeFile('dog-img.txt',res.body.message, err=>{
//             if(err) return console.log(err.message);
//             console.log('Random dog image saved to file!')
//         })
//     })

// })